package main

import (
	"encoding/json"
	"flag"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"nggs/tools/print"
	"nggs/util"
)

var (
	flagConfigFilePath = flag.String("cfg", "./cfg.json", "cfg file path, default = ./gen_static_data_json.json")
)

func main() {
	flag.Parse()

	cfg, err := loadConfig(*flagConfigFilePath)
	if err != nil {
		panic(err)
	}

	jsonDir, err := filepath.Abs(cfg.JsonDir)
	if err != nil {
		panic(err)
	}

	util.MustMkdirIfNotExist(jsonDir)

	if cfg.Debug {
		print.SetDebugMode(true)
	}

	type staticData struct {
		Global json.RawMessage
		Datas  []json.RawMessage
	}

	staticDatas := map[string]staticData{}

	err = util.Walk(cfg.JsonDir, "json", cfg.WhiteList, cfg.BlackList, func(path string, info os.FileInfo, name string, isInBlackList bool) bool {
		if isInBlackList {
			print.Infof("[%s]在黑名单中，跳过", path)
			return true
		}

		if strings.HasPrefix(info.Name(), "~$") {
			print.Debugf("跳过临时文件[%s]", path)
			return true
		}

		if name == "sd" {
			// 跳过sd.json
			return true
		}

		print.Infof("<- %s", path)

		jsonData, err := ioutil.ReadFile(path)
		if err != nil {
			print.Errorf("读取[%s]失败，%s", path, err)
			return true
		}

		sd := staticData{}

		err = json.Unmarshal(jsonData, &sd)
		if err != nil {
			print.Errorf("反序列化[%s]失败，%s", name, err)
			return true
		}

		staticDatas[name] = sd

		return true
	})
	if err != nil {
		panic(err)
	}

	jsonPath, _ := filepath.Abs(filepath.Join(cfg.OutputDir, "sd.json"))
	var jsonData []byte
	if cfg.Indent != "" {
		jsonData, err = json.MarshalIndent(staticDatas, "", cfg.Indent)
	} else {
		jsonData, err = json.Marshal(staticDatas)
	}

	if err != nil {
		print.Errorf("序列化失败，%s", err)
		return
	}
	err = ioutil.WriteFile(jsonPath, jsonData, 0766)
	if err != nil {
		print.Errorf("写入[%s]失败，%s", jsonPath, err)
		return
	}

	print.Infof("-> %s", jsonPath)
}
